package james.gan.bean;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import james.gan.context.anno.Service;
import james.gan.core.BeanDefinition;
import james.gan.core.Resource;
import james.gan.utils.ClassUtils;

/**
 * @Description: 注解资源加载
 * @author James
 * @date 2017/12/26
 */
public class AnnotationResourceLoader implements Resource {

  private String pkgPath;


  public AnnotationResourceLoader() {
    super();
  }

  public AnnotationResourceLoader(String pkgPath) {
    super();
    this.pkgPath = pkgPath;
  }

  @Override
  public Map<String, BeanDefinition> loadResources() {
    try {
      List<Class<?>> pkgClassInstance = ClassUtils.getClassList(pkgPath, true, Service.class);
      return pkgClassInstance.stream().map(i -> {
        Service annotation = i.getAnnotation(Service.class);
        DefaultBeanDefinition defaultBeanDefinition = new DefaultBeanDefinition(i);
        defaultBeanDefinition.setName(annotation.value());
        return defaultBeanDefinition;
      }).filter(i -> i != null).collect(Collectors.toMap(i -> i.getBeanID(), i -> i));
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  public String getPkgPath() {
    return pkgPath;
  }

  public void setPkgPath(String pkgPath) {
    this.pkgPath = pkgPath;
  }

}
